<?php
namespace Controllers;
use Models\CategoryModel;
use Models\CommentModel;
use Models\PostModel;

class PostController extends CommonController {
    public function add() {
        if (!empty($_POST)) {
            if (!$this->isLogin()) return $this->responseJson(401, '尚未登录');
            $cate_id = isset($_POST['cate_id']) ? intval($_POST['cate_id']) : 0;
            if (empty($cate_id)) return $this->responseJson(400, '请选择主题分类');
            $title = isset($_POST['title']) ? trim($_POST['title']) : '';
            if (empty($title)) return $this->responseJson(400, '请填写帖子主题');
            $content = isset($_POST['content']) ? $_POST['content'] : '';
            if (empty($content)) return $this->responseJson(400, '请填写帖子内容');
            $data = [
                'cate_id' => $cate_id,
                'title' => $title,
                'content' => $content,
                'user_id' => $_SESSION['user_id']
            ];
            $postModel = new PostModel();
            if ($postModel->add($data)) {
                return $this->responseJson(200, '帖子发布成功');
            } else {
                return $this->responseJson(400, '帖子发布失败');
            }
        } else {
            $this->noLoginJump();
            $cateModel = new CategoryModel();
            $cateList = $cateModel->getAllCategories();
            return $this->response('post/add', ['cateList' => $cateList]);
        }
    }

    public function evaluate () {
        if (!$this->isLogin()) return $this->responseJson(401, '尚未登录，请先登录');
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        if (empty($post_id)) return $this->responseJson(400, '帖子参数错误');
        $type = isset($_POST['type']) ? intval($_POST['type']) : 1;
        $postModel = new PostModel();
        if ($postModel->evaluate($type, $post_id)) {
            return $this->responseJson(200, '操作成功');
        } else {
            return $this->responseJson(400, '操作失败');
        }
    }

    public function detail() {
        $post_id = isset($_GET['post_id']) ? intval($_GET['post_id']) : 0;
        $postModel = new PostModel();
        $post = $postModel->getPostById($post_id);
        if (empty($post)) return '贴在不存在或者已删除';
        $commentModel = new CommentModel();

        $commentList = $commentModel->getCommentByPostId($post_id);
        return $this->response('post/detail', ['post' => $post, 'commentList' => $commentList]);
    }


}